package com.android.baseconfig.common.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.android.baseconfig.R;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.text.Normalizer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {

    private static long previousTime = 0;

    private static final String TAG = Util.class.getName();

    public static void showToast(Context context, String text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    public static void showToast(Context context, int resId) {
        Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    /**
     * 判断参数是否为空，做了trim操作，不需要trim的不要调用此方法<br>
     *
     * @param str
     * @return
     * @since LinkHome, 2015-7-21
     */
    public static boolean isEmpty(String str) {
        return str == null || StringUtils.isEmpty(str.trim());
    }

    public static void showDefaultDialog(Context context, String msg) {
        new AlertDialog.Builder(context).setTitle("Tip:").setMessage(msg).setNegativeButton("OK", null).show();
    }

    public static Date parseDate(final String s) {
        return parseDate(s, "yyyy-MM-dd HH:mm:ss");
    }

    public static Date parseDate(final String s, String pattern) {
        Date parse = null;
        if (isEmpty(s)) {
            return parse;
        }
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.getDefault());
        try {
            parse = simpleDateFormat.parse(s);
            return parse;
        } catch (ParseException ex) {
            Logc.e(Util.TAG, "", ex);
            return null;
        }
    }

    public static String safeSql(String upperCase) {
        final String normalizerText = normalizerText(upperCase);
        upperCase = "";
        if (normalizerText != null) {
            upperCase = normalizerText.toUpperCase(Locale.CHINESE);
        }
        final String normalizerText2 = normalizerText(upperCase);
        if (normalizerText2.startsWith("SELECT") && contains(normalizerText2, "UPDATE", "DELETE", "DROP", "CREATE", "INSERT")) {
            upperCase = "";
        } else {
            if (normalizerText2.startsWith("INSERT") && contains(normalizerText2, "UPDATE", "DELETE", "DROP", "CREATE")) {
                return "";
            }
            if (normalizerText2.startsWith("UPDATE") && contains(normalizerText2, "INSERT", "DELETE", "DROP", "CREATE")) {
                return "";
            }
            if (normalizerText2.startsWith("DROP") && contains(normalizerText2, "INSERT", "DELETE", "SELECT", "CREATE", "UPDATE")) {
                return "";
            }
            if (normalizerText2.startsWith("CREATE") && contains(normalizerText2, "INSERT", "DELETE", "SELECT", "DROP", "UPDATE")) {
                return "";
            }
            upperCase = normalizerText;
            if (normalizerText2.startsWith("DELETE")) {
                upperCase = normalizerText;
                if (contains(normalizerText2, "INSERT", "CREATE", "DROP", "UPDATE")) {
                    return "";
                }
            }
        }
        return upperCase;
    }

    private static boolean contains(final String s, final String... array) {
        for (int length = array.length, i = 0; i < length; ++i) {
            if (s.indexOf(array[i] + " ") != -1) {
                return true;
            }
        }
        return false;
    }

    public static String normalizerText(final String s) {
        String normalize = s;
        if (s != null) {
            normalize = Normalizer.normalize(s, Normalizer.Form.NFKC);
        }
        return normalize;
    }

    public static boolean isConectCurtenFamilyOnt(final Context context) {
        final String string = BaseSharedPreferences.getString(context, "mac");
        final String string2 = BaseSharedPreferences.getString(context, "LOCAL_ONT_MAC");
        if (isEmpty(string) || isEmpty(string2)) {
            setConnectType(context, false);
            return false;
        }
        if (string.equals(string2)) {
            return true;
        }
        setConnectType(context, false);
        return false;
    }

    public static boolean isLocalSwitchOpen(final Context context) {
        final boolean equals = "1".equals(BaseSharedPreferences.getString(context, "ISOPENNEARACCESS"));
        setConnectType(context, equals);
        return equals;
    }

    public static boolean isMobileNO(String paramString) {
        if (TextUtils.isEmpty(paramString)) {
            return false;
        }
        paramString = paramString.replace(" ", "");
        return paramString.matches("[1][3456789]\\d{9}");
    }

    public static boolean verify(String pass) {
        if (StringUtils.isEmpty(pass)) {
            ToastUtils.getInstance().showCustomToast(R.string.error_password_empty);
            return false;
        }
        if (((pass).length() > 20) || ((pass.length() < 6))) {
            ToastUtils.getInstance().showCustomToast(R.string.pswRule);
            return false;
        }
        if (!(pass).matches("^(?=.*[0-9].*)(?=.*[a-zA-Z].*).{6,16}$")) {
            ToastUtils.getInstance().showCustomToast(R.string.pswRule);
            return false;
        }
        if (!(pass).matches("[\\x21-\\x7e]+")) {
            ToastUtils.getInstance().showCustomToast(R.string.pwd_rule_zz);
            return false;
        }
        return true;
    }

    public static void setLoginType(final Context context, final boolean b) {
        String s;
        if (b) {
            s = "LOCAL_LOGIN";
        } else {
            s = "";
        }
        BaseSharedPreferences.setString(context, "LOGIN_TYPE", s);
    }

    public static void setLocalMode(final Context context, final boolean b) {
        String s;
        if (b) {
            s = "LOCAL_MODE";
        } else {
            s = "";
        }
        BaseSharedPreferences.setString(context, "LOCAL_MODE", s);
        if (b) {
            setConnectType(context, true);
        }
    }

    public static void setConnectType(final Context context, final boolean b) {
        String s;
        if (b) {
            s = "NEAR_CONNECT";
        } else {
            s = "";
        }
        BaseSharedPreferences.setString(context, "CONNECT_TYPE", s);
    }

    public static boolean isMainThread() {
        return Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId();
    }

    public static boolean isMatchLength(final String s, final int n) {
        return !s.isEmpty() && s.length() == n;
    }

    public static String replaceColon(final String s) {
        if (isEmpty(s) || !s.contains(":")) {
            return s;
        }
        return s.replaceAll(":", "");
    }

    public static String filterSQLInjection(String paramString) {
        return paramString.replaceAll(".*([';]+|(--)+).*", " ");
    }

    public static boolean ifContainsPic(final String s) {
        final String[] array = {".png", ".jpg", ".bmp", ".gif", ".jpeg"};
        final boolean b = false;
        final int length = array.length;
        int n = 0;
        boolean b2;
        while (true) {
            b2 = b;
            if (n >= length) {
                break;
            }
            if (s.toLowerCase(Locale.US).endsWith(array[n])) {
                b2 = true;
                break;
            }
            ++n;
        }
        return b2;
    }

    public static boolean isVideo(final String s) {
        final String[] array = {".mp4", ".3gp", ".rmvb", ".rm", ".mkv", ".avi", ".mpeg", ".wmv", "flv"};
        final boolean b = false;
        final int length = array.length;
        int n = 0;
        boolean b2;
        while (true) {
            b2 = b;
            if (n >= length) {
                break;
            }
            if (s.toLowerCase(Locale.US).endsWith(array[n])) {
                b2 = true;
                break;
            }
            ++n;
        }
        return b2;
    }

    public static boolean isMusic(final String s) {
        final String[] array = {".mp3", ".wma", ".wav"};
        final boolean b = false;
        final int length = array.length;
        int n = 0;
        boolean b2;
        while (true) {
            b2 = b;
            if (n >= length) {
                break;
            }
            if (s.toLowerCase(Locale.US).endsWith(array[n])) {
                b2 = true;
                break;
            }
            ++n;
        }
        return b2;
    }

    public static String toJsonStr(final Object o) {
        final Gson gson = new Gson();
        if (o == null) {
            return "";
        }
        return gson.toJson(o);
    }

    public static String parsingdata(final String s, final String s2) {
        if (s != null) {
            final String[] split = s.split(",");
            for (int length = split.length, i = 0; i < length; ++i) {
                final String[] split2 = split[i].split("=");
                if (1 < split2.length && split2[0].trim().equals(s2)) {
                    return split2[1].trim();
                }
            }
        }
        return "";
    }

    public static void gotoHomeActivity(final Activity activity) {
        if (null == activity) {
            return;
        }
        // Intent intent = new Intent(activity, LjjWebActivity.class);
        // intent.putExtra(LjjConstant.GO_URL, LjjConstant.URL_首页);
        // activity.startActivity(intent);
        activity.finish();
        activity.overridePendingTransition(R.anim.activity_open_enter, R.anim.activity_open_exit);
    }

    private static Map<String, String> getBaseList() {
        final HashMap<String, String> hashMap = new HashMap<String, String>();
        for (char c = 'a'; c <= 'z'; ++c) {
            hashMap.put(String.valueOf(c), String.valueOf(c));
        }
        for (char c2 = 'A'; c2 <= 'Z'; ++c2) {
            hashMap.put(String.valueOf(c2), String.valueOf(c2));
        }
        for (int i = 0; i <= 9; ++i) {
            hashMap.put(String.valueOf(i), String.valueOf(i));
        }
        hashMap.put(" ", " ");
        return hashMap;
    }

    public static String safePath(final String s) {
        final Map<String, String> baseList = getBaseList();
        baseList.put(":", ":");
        baseList.put("_", "_");
        baseList.put(".", ".");
        baseList.put("/", "/");
        baseList.put("-", "-");
        baseList.put("(", "(");
        baseList.put(")", ")");
        baseList.put(",", ",");
        baseList.put("@", "@");
        baseList.put(File.separator, File.separator);
        return filter(baseList, s);
    }

    private static String filter(final Map<String, String> map, final String s) {
        if (s == null) {
            return "";
        }
        final StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); ++i) {
            final String s2 = map.get(s.charAt(i) + "");
            if (s2 != null) {
                sb.append(s2);
            }
        }
        return sb.toString();
    }

    public static String getTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
    }

    public static String getTime(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(date);
    }

    public static String getTime(final String format) {
        return new SimpleDateFormat(format, Locale.getDefault()).format(new Date());
    }

    public static String getTime(String format, String timeStr) {
        String formatTime = "";
        Long time = 0L;
        try {
            time = Long.parseLong(timeStr);
            if (time > 0) {
                formatTime = new SimpleDateFormat(format, Locale.getDefault()).format(new Date(time));
            }
        } catch (NumberFormatException e) {
            return "";
        }
        return formatTime;
    }

    public static void setListViewHeight(final ListView listView, final int n) {
        final ListAdapter adapter = listView.getAdapter();
        if (adapter == null) {
            return;
        }
        int n2 = 0;
        for (int i = 0; i < n; ++i) {
            final View view = adapter.getView(i, null, listView);
            view.measure(0, 0);
            n2 += view.getMeasuredHeight();
        }
        final ViewGroup.LayoutParams layoutParams = listView.getLayoutParams();
        layoutParams.height = listView.getDividerHeight() * (n - 1) + n2;
        listView.setLayoutParams(layoutParams);
    }

    public static boolean isSdcardExist() {
        boolean b = false;
        if ("mounted".equals(Environment.getExternalStorageState())) {
            b = true;
        }
        return b;
    }

    public static String getTimeOnlyMd() {
        return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
    }

    public static int createID() {
        return (int) Math.floor(new SecureRandom().nextDouble() * 1.0E8);
    }

    public static String createSequenceID() {
        final StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 8; ++i) {
            final int n = (int) Math.floor(new SecureRandom().nextFloat() * 16.0f);
            String string = n + "";
            if (n > 9) {
                switch (n) {
                    default: {
                        string = "0";
                        break;
                    }
                    case 10: {
                        string = "A";
                        break;
                    }
                    case 11: {
                        string = "B";
                        break;
                    }
                    case 12: {
                        string = "C";
                        break;
                    }
                    case 13: {
                        string = "D";
                        break;
                    }
                    case 14: {
                        string = "E";
                        break;
                    }
                    case 15: {
                        string = "F";
                        break;
                    }
                }
            }
            sb.append(string);
        }
        return sb.toString();
    }

    public static String byte2String(final byte[] array) {
        return new String(array, Charset.forName("UTF-8"));
    }

    public static int dip2px(final Context context, final int n) {
        return (int) (n * context.getResources().getDisplayMetrics().density + 0.5f);
    }

    public static float dip2px(final Context context, final float n) {
        return n * context.getResources().getDisplayMetrics().density + 0.5f;
    }

    public static int px2dip(final Context context, final int n) {
        return (int) (n / context.getResources().getDisplayMetrics().density + 0.5f);
    }

    public static float px2dip(final Context context, final float n) {
        return n / context.getResources().getDisplayMetrics().density + 0.5f;
    }

    public static int sp2px(final Context context, final int n) {
        return (int) (n * context.getResources().getDisplayMetrics().scaledDensity + 0.5f);
    }

    public static float sp2px(final Context context, final float n) {
        return n * context.getResources().getDisplayMetrics().scaledDensity + 0.5f;
    }

    public static int px2sp(final Context context, final int n) {
        return (int) (n / context.getResources().getDisplayMetrics().scaledDensity + 0.5f);
    }

    public static float px2sp(final Context context, final float n) {
        return n / context.getResources().getDisplayMetrics().scaledDensity + 0.5f;
    }

    public static String formatMac(String s) {
        if (isEmpty(s)) {
            s = "";
        } else {
            final StringBuffer sb = new StringBuffer("");
            final String s2 = s.split("/")[0];
            for (int i = 0; i < s2.length() / 2; ++i) {
                sb.append(s2.substring(i * 2, i * 2 + 2)).append(':');
            }
            if (s.split("/").length > 1) {
                sb.insert(0, " ").insert(0, s.split("/")[1]);
            }
            if (sb.length() != 0) {
                return sb.substring(0, sb.length() - 1);
            }
        }
        return s;
    }

    public static boolean isHex(final String s) {
        if (!StringUtils.isEmpty(s)) {
            final boolean b = true;
            int n = 0;
            while (true) {
                final boolean b2 = b;
                if (n >= s.length()) {
                    return b2;
                }
                final char char1 = s.charAt(n);
                if ((char1 < '0' || char1 > '9') && (char1 < 'A' || char1 > 'F') && (char1 < 'a' || char1 > 'f')) {
                    break;
                }
                ++n;
            }
            return false;
        }
        return false;
    }

    @SuppressLint({"DefaultLocale"})
    public static String hexDecode(String upperCase) {
        if (StringUtils.isEmpty(upperCase) || upperCase.length() % 2 != 0 || !isHex(upperCase)) {
            return upperCase;
        }
        upperCase = upperCase.toUpperCase(Locale.US);
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(upperCase.length() / 2);
        for (int i = 0; i < upperCase.length(); i += 2) {
            byteArrayOutputStream.write("0123456789ABCDEF".indexOf(upperCase.charAt(i)) << 4 | "0123456789ABCDEF".indexOf(upperCase
                    .charAt(i + 1)));
        }
        return byte2String(byteArrayOutputStream.toByteArray());
    }

    public static boolean isFastClick() {
        boolean b = false;
        final long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - Util.previousTime < 500L) {
            b = true;
        }
        Util.previousTime = currentTimeMillis;
        return b;
    }

    public static String fileSizeChange(final String s) {
        if (isEmpty(s)) {
            return "";
        }
        try {
            final int int1 = Integer.parseInt(s.trim());
            if (int1 < 1024) {
                return int1 + "B";
            }
            if (int1 < 1048576) {
                return int1 / 1024 + "KB";
            }
            return int1 / 1024 / 1024 + "MB";
        } catch (NumberFormatException ex) {
            Logc.e(Util.TAG, "format str err, sizeStr= " + s);
            return "";
        }
    }

    public static Map<String, String> matchChargePolicy(String s) {
        final String errorMsg = ErrorCode.getErrorMsg("util_ver");
        final HashMap<String, String> hashMap = new HashMap<String, String>();
        final String[] split = s.split("#", 0);
        s = "";
        if ("Y".equals(split[0])) {
            s = errorMsg + split[split.length - 1] + ErrorCode.getErrorMsg("util_year");
        }
        if ("M".equals(split[0])) {
            s = errorMsg + split[split.length - 1] + ErrorCode.getErrorMsg("util_month");
        }
        if ("D".equals(split[0])) {
            s = errorMsg + split[split.length - 1] + ErrorCode.getErrorMsg("util_day");
        }
        if ("H".equals(split[0])) {
            s = errorMsg + split[split.length - 1] + ErrorCode.getErrorMsg("util_hours");
        }
        if ("F".equals(split[0])) {
            s = errorMsg + split[split.length - 1] + "M";
        }
        if ("MF".equals(split[0])) {
            s = errorMsg + split[2] + ErrorCode.getErrorMsg("util_monthsum") + split[split.length - 1] + "M";
        }
        hashMap.put("danwei", s);
        hashMap.put("value", split[1] + ErrorCode.getErrorMsg("util_yuan"));
        return hashMap;
    }

    @SuppressLint({"UseSparseArrays"})
    public static List<String> sortList(List<String> list) {
        if (!list.isEmpty() && list.size() != 1) {
            final List<Object> list2 = new ArrayList<Object>();
            final int[] array = new int[list.size()];
            final HashMap<Integer, Object> hashMap = new HashMap<Integer, Object>();
            for (int i = 0; i < list.size(); ++i) {
                final String[] split = list.get(i).split("#");
                array[i] = Integer.valueOf(split[split.length - 1]);
                hashMap.put(array[i], list.get(i));
            }
            Arrays.sort(array);
            int n = 0;
            while (true) {
                if (n >= array.length) {
                    break;
                }
                list2.add(hashMap.get(array[n]));
                ++n;
            }
        }
        return list;
    }

    public static String MD5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将字符串转换成字符串数组
        char[] pswdArray = str.toCharArray();
        byte[] pswdByte = new byte[pswdArray.length];
        //将字符转换成字节
        for (int i = 0; i < pswdArray.length; i++) {
            pswdByte[i] = (byte) pswdArray[i];
        }
        byte[] digest = md5.digest(pswdByte);
        //将得到的字节数组转换成十六进制数
        StringBuffer buff = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            int num = ((int) digest[i]) & 0xff;
            //如果不足16，加0填充
            if (num < 16) {
                buff.append("0");
            }
            buff.append(Integer.toHexString(num));
        }
        return buff.toString();
    }

    // 计算文件的 MD5 值
    public static String md5(File file) {
        if (file == null || !file.isFile() || !file.exists()) {
            return "";
        }
        FileInputStream in = null;
        String result = "";
        byte[] buffer = new byte[8192];
        int len;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer)) != -1) {
                md5.update(buffer, 0, len);
            }
            byte[] bytes = md5.digest();

            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static void closeSocket(Socket sct) {
        try {
            if (sct != null) {
                sct.close();
            }
        } catch (IOException e) {
            Logc.e(TAG, "ERROR when close Socket", e);
        } finally {
            sct = null;
        }

    }

    public static void deleteMedia(final File file, final Context context) {
        if (file == null || !file.exists()) {
            Logc.e(TAG, "file does not exist");
            return;
        }
        context.getContentResolver().delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "_id=" + file.hashCode(), null);
    }

    /**
     * 将字符串转换成long<br>
     *
     * @param str
     * @return
     * @since LinkHome, 2015-11-24
     */
    public static long fomartStrToLong(String str) {
        long value = 0;
        try {
            value = StringUtils.isEmpty(str) ? 0 : Long.valueOf(str);
        } catch (NumberFormatException e) {
            Logc.e(TAG, "");
        }

        return value;
    }

    public static String getTimeStr(final Long n) {
        return new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date(n));
    }

    public static boolean hasChineseChar(String str) {
        return isChineseChar(str) || hasChinesePunctuation(str);
    }

    public static boolean isChineseChar(String str) {
        boolean temp = false;
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            temp = true;
        }
        return temp;
    }

    /**
     * 是否包含中文字符<br>
     * 包含中文标点符号<br>
     *
     * @param str
     * @return
     */
    public static boolean hasChinesePunctuation(String str) {
        if (str == null) {
            return false;
        }
        char[] ch = str.toCharArray();
        for (char c : ch) {
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否是中文字符<br>
     * 包含中文标点符号<br>
     *
     * @param c
     * @return
     */
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) {
            return true;
        } else if (ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS) {
            return true;
        } else if (ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION) {
            return true;
        } else if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A) {
            return true;
        } else if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B) {
            return true;
        } else if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C) {
            return true;
        } else if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D) {
            return true;
        } else if (ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        } else if (ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    public static boolean hasSpaceChar(String str) {
        return str != null && str.contains(" ");
    }

    /**
     * 设置光标到未能本末尾
     *
     * @param editText
     */
    public static void setEditTextCursorEnd(EditText editText) {
        CharSequence charSequence = editText.getText();
        if (charSequence != null) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
    }
    /**
     * 获取手机卡类型，移动、联通、电信
     *
     */
    public static int getMobileType(Context context) {
        TelephonyManager iPhoneManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String iNumeric = iPhoneManager.getSimOperator();
        if (iNumeric != null && iNumeric.length() > 0) {
            Logc.i("num: " + iNumeric);
            if (iNumeric.equals("46000") || iNumeric.equals("46002")|| iNumeric.equals("46007")) {
                // 中国移动
                return 1;
            } else if (iNumeric.equals("46001") || iNumeric.equals("46004") || iNumeric.equals("46006")) {
                // 中国联通
                return 2;
            } else if (iNumeric.equals("46003") || iNumeric.equals("46005") || iNumeric.equals("46011")) {
                // 中国电信
                return 3;
            }
        }
        return 0;
    }

    public static boolean isValidMac(String macStr) {
        if (macStr == null || macStr.equals("")) {
            Logc.e(TAG, "it is not a valid macAddress, macStr is null");
            return false;
        }
        String macAddressRule = "([A-Fa-f0-9]{2}[-,:]){5}[A-Fa-f0-9]{2}";

        if (macStr.matches(macAddressRule)) {
            return true;
        } else {
            Logc.e(TAG, "it is not a valid macAddress");
            return false;
        }
    }
}
